package com.lv.suyiyong.hfr.fragment

import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SizeUtils
import com.bumptech.glide.Glide
import com.lv.common.base.BaseFragment
import com.lv.common.bean.CommonSelectedBean
import com.lv.common.imp.OnPositionTListener
import com.lv.common.ktx.LoadSrc
import com.lv.common.network.model.DataResult
import com.lv.common.utils.Constants
import com.lv.common.utils.MyUtils
import com.lv.common.widget.recyclerview.RecyclerViewAtViewPager2
import com.lv.common.widget.recyclerview.decoration.SpacesItemDecoration
import com.lv.service.bean.AdItemBean
import com.lv.service.bean.CompanyBean
import com.lv.service.bean.GoodsItemBean
import com.lv.service.bean.HomeTopBean
import com.lv.service.bean.TopIconItemBean
import com.lv.service.model.EditorViewModel
import com.lv.service.model.ServiceViewModel
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onFailure
import com.lv.service.network.onSuccess
import com.lv.service.room.company.CompanyItemBean
import com.lv.service.utils.YgxAroutPageKt
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.adapter.BannerHomeBrandAdapter
import com.lv.suyiyong.hfr.adapter.BannerHomeFactoryAdapter
import com.lv.suyiyong.hfr.adapter.FactoryAdapter
import com.lv.suyiyong.hfr.adapter.HomeTopTabAdapter
import com.lv.suyiyong.hfr.adapter.HomeWholeAdapter
import com.lv.suyiyong.hfr.databinding.FragmentCategoryHomeBinding
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.youth.banner.Banner
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.withContext
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2023/3/10 3:49 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：首页找厂家 fragment
 */
class HomeCategoryFragment : BaseFragment(), View.OnClickListener {
    private var page: Int = 1
    private var pageSize: Int = Constants.pageSize
    private var mCategory: CommonSelectedBean? = null
    private var mFristLoading = true
    private val mParamsMap = mutableMapOf<String, String>()
    private var mAdapter: FactoryAdapter? = null
    private var mTabAdapter: HomeTopTabAdapter? = null
    private var mFactoryBannerAdapter: BannerHomeFactoryAdapter? = null
    private var mBrandBannerAdapter: BannerHomeBrandAdapter? = null
    private var mLocationBannerAdapter: BannerHomeBrandAdapter? = null
    private var mBannerAdapter: BannerImageAdapter<AdItemBean>? = null
    private var mWholeAdapter: HomeWholeAdapter? = null
    private val mBenas = mutableListOf<CompanyItemBean>()
    private val mBrandBeans = mutableListOf<List<GoodsItemBean>>()
    private val mLocationBeans = mutableListOf<List<GoodsItemBean>>()
    private val mWholeBeans = mutableListOf<GoodsItemBean>()
    private val mFacBanners = mutableListOf<CompanyItemBean>()
    private val mBannerDatas = mutableListOf<AdItemBean>()
    private val mTabs = mutableListOf<TopIconItemBean>()

    //    private var mRvTab: RecyclerView? = null
    private var mBannerFactory: Banner<*, *>? = null
    private var mBannerBrand: Banner<*, *>? = null
    private var mBannerLocation: Banner<*, *>? = null
    private var mBannerHeader: Banner<*, *>? = null
    private val mEditorViewModel: EditorViewModel by activityViewModels()
    private val viewModelService: ServiceViewModel by viewModel()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    private var mBinding: FragmentCategoryHomeBinding? = null
    override fun getLayoutRes() = R.layout.fragment_category_home

    override fun bindView(view: View, savedInstanceState: Bundle?): ViewDataBinding {
        mBinding = FragmentCategoryHomeBinding.bind(view).apply {
        }
        return mBinding!!
    }


    override fun onResume() {
        super.onResume()
        LogUtils.e("aaaaaaaaaonResume", mCategory?.name)
        if (mFristLoading) {
            mFristLoading = false
            bottomPage()
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        LogUtils.e("aaaaaaaaaaaaaaonHiddenChanged", mCategory?.name, hidden.toString())
    }

    override fun initConfig() {
        super.initConfig()
        mParamsMap["code"] = "0"

    }


    override fun initData() {
        super.initData()
        arguments?.let {
            mCategory = it.getParcelable("name")
        }
        LogUtils.e("aaaaaaaaaaaaaaoninitData", mCategory?.name)
        initAdapter()

    }

    private fun initAdapter() {
        mAdapter = FactoryAdapter(mBenas)
        mBinding?.rvContent?.adapter = mAdapter
        mBinding?.rvContent?.addItemDecoration(
            SpacesItemDecoration(
                SizeUtils.dp2px(10.0f),
                SizeUtils.dp2px(10.0f),
                true
            )
        )
        val topHeader = View.inflate(context, R.layout.fragment_factory_header, null)
        var name = mCategory?.name ?: ""
        val mClContainerHeader = topHeader.findViewById<ConstraintLayout>(R.id.cl_container_header)
        if (name == "推荐工厂") {
            name = ""
            homePage()
            mClContainerHeader.visibility = View.VISIBLE
            val mIvTagFactory = topHeader.findViewById<ImageView>(R.id.iv_tag_factory)
            val mIvTagBrand = topHeader.findViewById<ImageView>(R.id.iv_tag_brand)
            val mIvTagLocation = topHeader.findViewById<ImageView>(R.id.iv_tag_location)
            val mRvTab = topHeader.findViewById<RecyclerView>(R.id.rv_tab)
            val mRvWhole = topHeader.findViewById<RecyclerViewAtViewPager2>(R.id.rv_whole)
            val mClFactory = topHeader.findViewById<ConstraintLayout>(R.id.cl_factory)
            val mClLocation = topHeader.findViewById<ConstraintLayout>(R.id.cl_location)
            val mClBrand = topHeader.findViewById<ConstraintLayout>(R.id.cl_brand)
            mBannerFactory = topHeader.findViewById<Banner<*, *>>(R.id.banner_factory)
            mBannerBrand = topHeader.findViewById<Banner<*, *>>(R.id.banner_brand)
            mBannerLocation = topHeader.findViewById<Banner<*, *>>(R.id.banner_location)
            mBannerHeader = topHeader.findViewById<Banner<*, *>>(R.id.banner_header)
            val mTvLookMore = topHeader.findViewById<TextView>(R.id.tv_look_more)
            mClFactory.setOnClickListener(this@HomeCategoryFragment)
            mClLocation.setOnClickListener(this@HomeCategoryFragment)
            mClBrand.setOnClickListener(this@HomeCategoryFragment)
            mTvLookMore.setOnClickListener(this@HomeCategoryFragment)
            mTabAdapter = HomeTopTabAdapter(mTabs)
            mRvTab.adapter = mTabAdapter
            mTabAdapter?.onViewClickListener = OnPositionTListener { position, data ->
                val tag = data?.tag
                YgxAroutPageKt.aroutPager(requireContext(), tag)
            }
            mWholeAdapter = HomeWholeAdapter(mWholeBeans)
            mRvWhole.adapter = mWholeAdapter
            mIvTagFactory.LoadSrc("https://suyiyong.oss-cn-hangzhou.aliyuncs.com/iOS/projectPic/hfr/home_twoCard0.png")
            mIvTagBrand.LoadSrc("https://suyiyong.oss-cn-hangzhou.aliyuncs.com/iOS/projectPic/hfr/home_twoCard6.png")
            mIvTagLocation.LoadSrc("https://suyiyong.oss-cn-hangzhou.aliyuncs.com/iOS/projectPic/hfr/home_twoCard5.png")
            initBannerAdapter()
//            bannerObserver()
        } else {
            mClContainerHeader.visibility = View.GONE
        }
        mParamsMap["fname"] = name
        mAdapter?.addHeaderView(topHeader)

    }

    private fun homePage() {
        val homePageMap = mutableMapOf("code" to "0", "province" to "湖北")
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                withContext(myScope.coroutineContext) {
                    viewModelService.homePage(homePageMap)
                }
            parseHomePageResult(result)
        }
    }

    private fun parseHomePageResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<HomeTopBean> { code, data, message, result ->
                val topIcon = data?.topIcon
                mTabs.clear()
                topIcon?.let { mTabs.addAll(it) }
                mTabAdapter?.notifyDataSetChanged()
                val mfac = data?.mfac
                mFacBanners.clear()
                mfac?.let { mFacBanners.addAll(it) }
//                refreshFactoryBanner()
                mFactoryBannerAdapter?.notifyDataSetChanged()

                val brand = data?.brand
                val brands = brand?.chunked(2)
                mBrandBeans.clear()
                brands?.let { mBrandBeans.addAll(it) }
                mBrandBannerAdapter?.notifyDataSetChanged()

                val fac = data?.fac
                val facs = fac?.chunked(2)
                mLocationBeans.clear()
                facs?.let { mLocationBeans.addAll(it) }
                mLocationBannerAdapter?.notifyDataSetChanged()

                val batch = data?.batch
                mWholeBeans.clear()
                batch?.let { mWholeBeans.addAll(it) }
                mWholeAdapter?.notifyDataSetChanged()

                val topAd = data?.topAd
                mBannerDatas.clear()
                topAd?.let { mBannerDatas.addAll(it) }
                mBannerAdapter?.notifyDataSetChanged()

                val hotSearch = data?.hotSearch
                mEditorViewModel.liveSearchData.postValue(hotSearch)
            }
            onBizError<Any> { code, message, data ->
            }
        }
        data.onFailure {
        }
    }

//    private suspend fun refreshFactoryBanner() {
//        withContext(Dispatchers.IO) {
//            myScope.async {
//                mFactoryBannerAdapter?.notifyDataSetChanged()
//            }.await()
//        }
//    }


    private fun bottomPage() {
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                withContext(myScope.coroutineContext) {
                    viewModelService.bottomPage(
                        page, pageSize, mParamsMap
                    )
                }
            parseResult(result)
        }
    }

    private fun parseResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<CompanyBean> { code, data, message, result ->
                val items = data?.items
                MyUtils.recyclerviewSetData(
                    page, pageSize, mBinding?.refreshLayout, mBenas, items, mAdapter
                )
                if (mBenas.isEmpty()) {
                    mAdapter?.setEmptyView(getEmptyView(mBinding?.rvContent!!))
                }

            }
            onBizError<CompanyBean> { code, message, data ->
                loadFinished()
                mBinding?.refreshLayout?.finishRefresh()
                mBinding?.refreshLayout?.finishLoadMore()
            }
        }
        data.onFailure {
            loadFinished()
            mBinding?.refreshLayout?.finishRefresh()
            mBinding?.refreshLayout?.finishLoadMore()
        }
    }

    override fun initEvents() {
        super.initEvents()
        mBinding?.refreshLayout?.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                page = 1
                bottomPage()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                page++
                bottomPage()
            }
        })
    }

    /**
     * 初始化轮播图Adapter
     */
    private fun initBannerAdapter() {
        mFactoryBannerAdapter = BannerHomeFactoryAdapter(mFacBanners)
        mBannerFactory?.adapter = mFactoryBannerAdapter
        mBannerFactory?.setIntercept(true)
        mBrandBannerAdapter = BannerHomeBrandAdapter(mBrandBeans)
        mBannerBrand?.adapter = mBrandBannerAdapter
        mBannerBrand?.setIntercept(true)

        mLocationBannerAdapter = BannerHomeBrandAdapter(mLocationBeans)
        mBannerLocation?.adapter = mLocationBannerAdapter
        mBannerLocation?.setIntercept(true)

        mBannerAdapter = object : BannerImageAdapter<AdItemBean>(mBannerDatas) {
            override fun onBindView(
                holder: BannerImageHolder?,
                data: AdItemBean?,
                position: Int,
                size: Int
            ) {
                Glide.with(requireContext())
                    .load(data?.image)
                    .into(holder?.imageView!!)
            }
        }
        mBannerHeader?.adapter = mBannerAdapter
        mBannerHeader?.setIntercept(true)
    }

    /**
     * 设置Banner适配器
     */
//    private fun bannerObserver() {
//
//        mBannerFactory?.addBannerLifecycleObserver(viewLifecycleOwner)
//            ?.setAdapter(mFactoryBannerAdapter)
//            ?.setIntercept(true)
//
//        mBannerBrand?.addBannerLifecycleObserver(viewLifecycleOwner)
//            ?.setAdapter(mBrandBannerAdapter)
//            ?.setIntercept(true)
//
//        mBannerLocation?.addBannerLifecycleObserver(viewLifecycleOwner)
//            ?.setAdapter(mLocationBannerAdapter)
//            ?.setIntercept(true)
//
//
//        mBannerHeader?.addBannerLifecycleObserver(viewLifecycleOwner)
//            ?.setAdapter(mBannerAdapter)
//            ?.setIntercept(true)
//
//    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.cl_factory -> {//必找工厂榜
                YgxAroutPageKt.aroutPager(requireContext(), "7")
            }

            R.id.cl_location -> {//本地工厂
                YgxAroutPageKt.aroutPager(requireContext(), "5")
            }

            R.id.cl_brand -> {//品牌工厂
                YgxAroutPageKt.aroutPager(requireContext(), "6")
            }

            R.id.tv_look_more -> {//批发好价
                YgxAroutPageKt.aroutPager(requireContext(), "8")
            }
        }
    }

    companion object {
        fun newInstance(name: CommonSelectedBean): HomeCategoryFragment {
            val args = Bundle()
            args.putParcelable("name", name)
            val fragment = HomeCategoryFragment()
            fragment.arguments = args
            return fragment
        }
    }


}